// pages/shopping-trolley/shopping-trolley.js
const SERVICE = require("../../service.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsData: [],
    checkAllStauts: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this,td = this.data;
    let openid = wx.getStorageSync("token");    
    ShoppingCartDetails(_this);    
    let checkAllStatus = isCheckAll(td.goodsData, 'radioChecked');
    this.setData({
      checkAllStauts: checkAllStatus == false ? false : true
    });

    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   *带 _ 内部方法
   * 
   * 
   * **/

  _CStart(e) {
    this.StartX = e.changedTouches[0].pageX;
  },
  _CMove(e) {
    let Item = e.currentTarget.dataset.index;
    this.MoveX = e.changedTouches[0].pageX;
    if (this.StartX - this.MoveX > 60) {
      this.setData({
        ShowActive: true,
        Item
      });
    } else if (this.MoveX > this.StartX + 60) {
      this.setData({
        ShowActive: false,
        Item
      });
    }
  },
  _CRemove(e) {
    let _this = this,
    id = e.currentTarget.dataset.id;
    let openid = wx.getStorageSync("token");    
    wx.showModal({
      title: "提示",
      content: "确定删除该商品吗？",
      confirmColor: "#31AEFE",
      success: function (res) {
        if (res.confirm) {
          SERVICE.deleteShoppingCart({ id, openid},(status,data)=>{
            if(status){
              ShoppingCartDetails(_this);
              _this.setData({
                ShowActive: false
              });
            }
          });
        } else if (res.cancel) {
          _this.setData({
            ShowActive: false
          });
        }
      }
    });
  },
  _CRadio(e) {
    let td = this.data,
    radioItem = e.currentTarget.dataset.index;
    td.goodsData[radioItem].radioChecked = !td.goodsData[radioItem].radioChecked;
    let totalPrices = getTotalPrices(this,td.goodsData, 'radioChecked');
    let checkAllStatus = isCheckAll(td.goodsData, 'radioChecked');
    
    this.setData({
      goodsData: td.goodsData,
      totalPrices,
      checkAllStauts: checkAllStatus == false ? false : true
    });
  },
  checkAll() {
    let td = this.data;
    let checkAllStatus = isCheckAll(td.goodsData, 'radioChecked');
    if (checkAllStatus == false) {
      getChecked(this,td.goodsData, true, (data, totalPrices) => {
        this.setData({
          goodsData: data,
          totalPrices,
          totalPrices2: totalPrices,
          checkAllStauts:true
        });
      });
    }else{
      getChecked(this,td.goodsData, false, (data, totalPrices) => {
        this.setData({
          goodsData: data,
          totalPrices,
          totalPrices2: totalPrices,
          checkAllStauts: false
        });
      });
    }

  },
  minus(e){
    let _this = this,
      td = this.data,
      max = e.currentTarget.dataset.max,
      index = e.currentTarget.dataset.index,
      rec_id = e.currentTarget.dataset.recid;
    let openid = wx.getStorageSync("token");
      
    if (parseFloat(td.goodsData[index].goods_number) > 1){
      td.goodsData[index].goods_number--;
      SERVICE.updateCart({ 
        rec_id, goods_number: td.goodsData[index].goods_number,
        openid	}, (status,data) => {
        if (status){
          _this.setData({
            goodsData: td.goodsData,
            totalPrices: getTotalPrices(_this, td.goodsData)
            
          });
        }
      });
      }
    
  },
  add(e){
    let _this = this,
        td = this.data,
        max = e.currentTarget.dataset.max,
        index = e.currentTarget.dataset.index,
        rec_id = e.currentTarget.dataset.recid;
    let openid = wx.getStorageSync("token");
    console.log(index);
    if (parseFloat(td.goodsData[index].goods_number) < parseInt(max)){
      td.goodsData[index].goods_number ++;
      SERVICE.updateCart({ rec_id, goods_number: td.goodsData[index].goods_number, 
      openid }, (status, data) => {
        console.log('add:', data);
        if (status) {
          // ShoppingCartDetails(_this);
          getTotalPrices(_this, td.goodsData);
         _this.setData({
           goodsData: td.goodsData,
           totalPrices: getTotalPrices(_this, td.goodsData)
         });
        }
      });
    }else{
      wx.showToast({
        title: "没有存货啦~",
        icon:"none",
        mask:true
      });
    }
  },
  formSubmit(e) {
    let openid = wx.getStorageSync("token");        
    let td = this.data,form_data = e.detail.value,goodsId_array = [];
    
    if (td.selected_num){
     for (let i in form_data) {
       if (form_data[i]) {
         goodsId_array.push(form_data[i]);
       }
     }
      let goodsId_array2 = [];
     for (let e = 0; e < td.goodsData.length; e++){
       if (td.goodsData[e].radioChecked == true){
         goodsId_array2.push(td.goodsData[e].goods_id);         
       }
     }
      console.log(goodsId_array, goodsId_array2);
     
    //  wx.showLoading({
    //    title: "提交中...",
    //    mask: true
    //  });
    //   SERVICE.getRepertory({
    //     goods_id: JSON.stringify(goodsId_array), openid 
    //   },(status,res)=>{
    //     console.log(res);
    //     wx.hideLoading();
    //     if(res.code == 200){
         
    //     }else{
    //       wx.showToast({
    //         title: res.data.message,
    //         icon: "none",
    //         mask: true
    //       });
    //     }
    //   });  

      if (td.totalPrices2 >= td.goodsData2.min_money) {
        SERVICE.getRepertory({ goods_id: JSON.stringify(goodsId_array2), openid }, (status, data) => {
          console.log("提交：", data);
          if (status) {
            wx.navigateTo({
              url: "../submit-order/submit-order?goodsId_array=" + JSON.stringify(goodsId_array),
              success: function (res) { },
              fail: function (res) { },
              complete: function (res) { },
            });
          } else {
            wx.showToast({
              title: data.message,
              icon: "none",
              duration: 1500,
              mask: true
            });
          }
        });
      } else {
        wx.showToast({
          title: "满￥" + td.goodsData2.min_money + "元才能提交订单哦！",
          icon: "none",
          duration: 1500,
          mask: true
        });
      }
    
   }
  }
})

function ShoppingCartDetails(e){
  let openid = wx.getStorageSync("token");
  
  wx.showNavigationBarLoading();  
  SERVICE.getShoppingCartDetails({ openid }, (resStatus, data) => {
    wx.hideNavigationBarLoading();
    console.log("购物车数据:", data);
    if (resStatus) {
      for (let i = 0; i < data.goods_list.length; i++) {
        data.goods_list[i].radioChecked = false;
      }
      e.setData({
        goodsData: data.goods_list,
        goodsData2: data,
        totalPrices: getTotalPrices(e, data.goods_list)
      });
    }else{
      e.setData({
        goodsData:0,
        goodsData2:0,
        totalPrices: getTotalPrices(e, 0)
      });
    }
  });
}
  
// 计算总价
function getTotalPrices(e,data, param) {
  let totalPrices = 0, totalPrices2 = 0,selected_num = 0;
  for (let i = 0; i < data.length; i++) {
    if (data[i].radioChecked == true) {
      selected_num ++;
      totalPrices2 += (parseFloat(data[i].goods_price) * parseInt(data[i].goods_number));
      
    }
    // console.log(typeof (data[i].goods_price * data[i].goods_number).toFixed(2));
    data[i].itemTotalPrices = (data[i].goods_price * data[i].goods_number).toFixed(2);
    totalPrices += (parseFloat(data[i].goods_price) * parseInt(data[i].goods_number));
  }
  e.setData({
    selected_num,
    totalPrices2: totalPrices2.toFixed(2)
  });
  return totalPrices.toFixed(2);
}

// 全选
function getChecked(e,data, stauts, fun) {
  let totalPrices = 0, selected_num = 0;
  for (let i = 0; i < data.length; i++) {
    data[i].radioChecked = stauts;
    stauts ? totalPrices += (parseFloat(data[i].goods_price) * data[i].goods_number): totalPrices = 0;
    if (stauts == true){
      selected_num++;
    }
  }
  e.setData({
    selected_num,
  });
  return typeof fun === "function" && fun(data, totalPrices.toFixed(2), stauts);
}


function isCheckAll(data, param) {
  for (let i = 0; i < data.length; i++) {
    if (data[i][param] == false) {
      return false
    }

  }
}